<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>模板变量配置</span>
        <el-button style="float: right; padding: 3px 0" link @click="goBack">返回</el-button>
      </div>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form :model="templateInfo" label-width="100px" size="small">
            <el-form-item label="模板名称">
              <el-input v-model="templateInfo.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="模板类型">
              <el-input v-model="templateInfo.type" disabled></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      
      <el-divider content-position="center">变量列表</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="24" class="mb20">
          <el-button-group>
            <el-button type="primary" icon="el-icon-plus" @click="handleAddVariable">添加变量</el-button>
            <el-button type="success" icon="el-icon-check" @click="handleSaveVariables">保存变量</el-button>
          </el-button-group>
        </el-col>
      </el-row>
      
      <el-table :data="variableList" size="small" border style="width: 100%">
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="name" label="变量名称" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.name" placeholder="请输入变量名称"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="变量描述">
          <template slot-scope="scope">
            <el-input v-model="scope.row.description" placeholder="请输入变量描述"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="defaultValue" label="默认值" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.defaultValue" placeholder="请输入默认值"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              link
              icon="el-icon-delete"
              @click="handleDeleteVariable(scope.$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { getTemplate, listTemplateVariables, saveTemplateVariables } from "@/api/qep/certificate/template";

export default {
  name: "TemplateVariables",
  data() {
    return {
      // 模板ID
      templateId: null,
      // 模板信息
      templateInfo: {
        id: null,
        name: '',
        type: '',
      },
      // 变量列表
      variableList: [],
      // 原始变量列表（用于比较变更）
      originalVariables: []
    };
  },
  created() {
    // 从路由获取模板ID
    this.templateId = this.$route.query.id;
    if (this.templateId) {
      this.getTemplateInfo();
      this.getVariableList();
    } else {
      this.$modal.msgError("未指定模板ID");
      this.goBack();
    }
  },
  methods: {
    // 获取模板信息
    getTemplateInfo() {
      getTemplate(this.templateId).then(response => {
        this.templateInfo = response.data;
      }).catch(() => {
        this.$modal.msgError("获取模板信息失败");
      });
    },
    
    // 获取变量列表
    getVariableList() {
      listTemplateVariables(this.templateId).then(response => {
        this.variableList = response.data || [];
        // 深拷贝保存原始变量列表
        this.originalVariables = JSON.parse(JSON.stringify(this.variableList));
      }).catch(() => {
        this.$modal.msgError("获取变量列表失败");
      });
    },
    
    // 添加变量
    handleAddVariable() {
      this.variableList.push({
        templateId: this.templateId,
        name: '',
        description: '',
        defaultValue: ''
      });
    },
    
    // 删除变量
    handleDeleteVariable(index) {
      this.variableList.splice(index, 1);
    },
    
    // 保存变量
    handleSaveVariables() {
      // 验证变量名称不能为空
      for (let i = 0; i < this.variableList.length; i++) {
        if (!this.variableList[i].name) {
          this.$modal.msgError(`第${i+1}行的变量名称不能为空`);
          return;
        }
      }
      
      // 所有变量设置模板ID
      this.variableList.forEach(variable => {
        variable.templateId = this.templateId;
      });
      
      // 保存变量
      saveTemplateVariables(this.variableList).then(() => {
        this.$modal.msgSuccess("保存成功");
        this.getVariableList(); // 刷新数据
      }).catch(() => {
        this.$modal.msgError("保存失败");
      });
    },
    
    // 返回
    goBack() {
      // 检查是否有未保存的修改
      if (JSON.stringify(this.variableList) !== JSON.stringify(this.originalVariables)) {
        this.$confirm('有未保存的修改，确定要离开吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push({ path: '/certificate/template' });
        }).catch(() => {});
      } else {
        this.$router.push({ path: '/certificate/template' });
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  margin-top: 0;
}
.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
.mb20 {
  margin-bottom: 20px;
}
</style> 